package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ChapterLessonLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewChapterLessonLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChapterLessonLogic {
	return &ChapterLessonLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ChapterLessonLogic) ChapterLesson(req *types.IdForm) (resp []types.ChapterLesson, err error) {
	course := &models.Course{
		Id: req.Id,
	}
	db.GetData(course)
	if course.Type == 20 {
		return nil, errors.New("非章节课程")
	}
	cond := xb.Eq{"course_id": req.Id}

	lessons := []models.Lesson{}
	db.FindDatas(&lessons, cond, "sort_num ASC,id ASC")
	mpl := make(map[int][]*types.ChapterLesson)
	for _, lesson := range lessons {
		tmp := &types.ChapterLesson{}
		copier.Copy(tmp, lesson)
		tmp.Type = "lesson"
		tmp.RowId = tmp.Type + utils.IntToString(lesson.Id)
		tmp.Children = []*types.ChapterLesson{}
		mpl[lesson.ChapterId] = append(mpl[lesson.ChapterId], tmp)
	}

	chapteies := []models.Chapter{}
	db.FindDatas(&chapteies, cond, "sort_num ASC,id ASC")
	for _, v := range chapteies {
		tmp := &types.ChapterLesson{}
		copier.Copy(tmp, v)
		tmp.Type = "chapter"
		tmp.RowId = tmp.Type + utils.IntToString(v.Id)
		if ost, ok := mpl[v.Id]; ok {
			tmp.Children = ost
		} else {
			tmp.Children = []*types.ChapterLesson{}
		}
		resp = append(resp, *tmp)
	}

	return resp, nil
}
